﻿#region 命名空间

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

#endregion

namespace Sharp.Infrastructure.Security
{
    /// <summary>
    ///     对称加解密算法
    /// </summary>
    public class Reversible
    {
        /// <summary>
        ///     对称算法加密
        /// </summary>
        /// <param name="datastr">要加密的字符串</param>
        /// <param name="keystr">加密钥匙串</param>
        /// <returns>string</returns>
        public static string Encrypt(string datastr, string keystr)
        {
            using (DESCryptoServiceProvider desc = new DESCryptoServiceProvider()) //des进行加密
            {
                byte[] key = Encoding.Unicode.GetBytes(keystr);
                byte[] data = Encoding.Unicode.GetBytes(datastr);
                using (MemoryStream ms = new MemoryStream()) //存储加密后的数据
                {
                    CryptoStream cs = new CryptoStream(ms, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);
                    cs.Write(data, 0, data.Length); //进行加密
                    cs.FlushFinalBlock();
                    return Convert.ToBase64String(ms.ToArray()); //取加密后的数据
                }
            }
        }

        /// <summary>
        ///     对称算法解密
        /// </summary>
        /// <param name="datastr">要解密的字符串</param>
        /// <param name="keystr">加密钥匙串</param>
        /// <returns>string</returns>
        public static string Decrypt(string datastr, string keystr)
        {
            using (DESCryptoServiceProvider desc = new DESCryptoServiceProvider())
            {
                byte[] key = Encoding.Unicode.GetBytes(keystr);
                byte[] data = Convert.FromBase64String(datastr);
                using (MemoryStream ms = new MemoryStream()) //存储解密后的数据
                {
                    CryptoStream cs = new CryptoStream(ms, desc.CreateDecryptor(key, key), CryptoStreamMode.Write);
                    cs.Write(data, 0, data.Length); //解密数据
                    cs.FlushFinalBlock();
                    return Encoding.Unicode.GetString(ms.ToArray());
                }
            }
        }
    }
}